import 'package:get/get.dart';
import 'package:flutter/material.dart';  // 添加Flutter Material导入，包含Color类
import '../../auth/controllers/auth_controller.dart';
import '../../../services/user_service.dart';
import '../../../services/product_service.dart';
import '../../../services/device_service.dart';
import '../../../services/alert_log_service.dart';
import '../../../repositories/data_repository.dart';
import '../../../models/alert_log_model.dart';
import 'dart:async';

class HomeController extends GetxController {
  // 产品统计数据
  var productCount = 0.obs;
  var productsWithoutModelCount = 0.obs;
  
  // 设备统计数据
  var deviceTotalCount = 0.obs;
  var deviceOnlineCount = 0.obs;
  var deviceOfflineCount = 0.obs;
  var deviceInactiveCount = 0.obs;
  var deviceDisabledCount = 0.obs;
  
  // 告警日志数据
  var alertLogs = <AlertLog>[].obs;
  var alertLogsTotal = 0.obs;
  var unconfirmedAlertCount = 0.obs;
  var isLoadingAlerts = false.obs;
  
  // 告警状态统计数据
  var alertGeneratedCount = 0.obs;  // 状态0: 产生
  var alertRecoveredCount = 0.obs;  // 状态1: 恢复
  var alertConfirmedCount = 0.obs;  // 状态2: 已确认
  
  // 加载状态
  var isLoading = true.obs;             // 初始加载状态
  var isRefreshing = false.obs;         // 下拉刷新状态

  // 服务实例
  late final ProductService _productService;
  late final DeviceService _deviceService;
  late final AlertLogService _alertLogService;
  late final DataRepository _dataRepository; // 保留用于获取颜色代码
  
  // 延迟获取AuthController，避免初始化时找不到的问题
  late final AuthController _authController;
  
  // 获取UserService实例
  late final UserService _userService;
  
  // 用户信息getter
  UserService get userService => _userService;
  
  // 登出方法
  void logout() {
    _authController.logout();
  }
  
  // 刷新用户信息
  Future<void> refreshUserInfo() async {
    try {
      isRefreshing.value = true;
      await _userService.getUserInfo();
    } catch (e) {
      Get.snackbar(
        '获取用户信息失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isRefreshing.value = false;
    }
  }
  
  // 获取产品统计数据 - 使用缓存服务
  Future<void> loadProductStatistics() async {
    try {
      final statistics = await _productService.getHomeStatistics();
      productCount.value = statistics['productCount'] ?? 0;
      productsWithoutModelCount.value = statistics['productsWithoutModelCount'] ?? 0;
    } catch (e) {
      debugPrint('获取产品统计数据失败: $e');
      Get.snackbar(
        '获取产品统计数据失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  // 获取设备统计数据 - 使用缓存服务
  Future<void> loadDeviceStatistics() async {
    try {
      final statistics = await _deviceService.getHomeStatistics();
      deviceTotalCount.value = statistics['totalCount'] ?? 0;
      deviceOnlineCount.value = statistics['onlineCount'] ?? 0;     // 状态码1：在线
      deviceOfflineCount.value = statistics['offlineCount'] ?? 0;   // 状态码2：离线
      deviceInactiveCount.value = statistics['inactiveCount'] ?? 0; // 状态码0：未激活
      deviceDisabledCount.value = statistics['disabledCount'] ?? 0; // 状态码3：禁用
    } catch (e) {
      debugPrint('获取设备统计数据失败: $e');
      Get.snackbar(
        '获取设备统计数据失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  // 获取最新告警日志和告警状态统计 - 使用缓存服务
  Future<void> loadRecentAlertLogs() async {
    debugPrint('准备加载告警日志，当前isLoadingAlerts=${isLoadingAlerts.value}');
    
    try {
      isLoadingAlerts.value = true;
      
      debugPrint('开始请求告警日志数据...');
      
      // 从缓存服务获取数据
      final stats = await _alertLogService.getHomeStatistics();
      
      debugPrint('成功获取告警日志，总数：${stats['total']}');
      
      // 更新状态
      alertLogs.value = stats['logs'];
      alertLogsTotal.value = stats['total'];
      unconfirmedAlertCount.value = stats['unconfirmedCount'];
      alertGeneratedCount.value = stats['generatedCount'];
      alertRecoveredCount.value = stats['recoveredCount'];
      alertConfirmedCount.value = stats['confirmedCount'];
      
    } catch (e) {
      debugPrint('获取告警日志失败: $e');
      // 出错时清空数据，避免显示过时信息
      alertLogs.clear();
      // 设置默认值
      alertLogsTotal.value = 0;
      unconfirmedAlertCount.value = 0;
      alertGeneratedCount.value = 0;
      alertRecoveredCount.value = 0;
      alertConfirmedCount.value = 0;
    } finally {
      isLoadingAlerts.value = false;
    }
  }
  
  // 确认告警
  Future<void> confirmAlert(int logId) async {
    try {
      final success = await _alertLogService.confirmAlert(logId);
      if (success) {
        // 刷新告警列表
        loadRecentAlertLogs();
        Get.snackbar(
          '成功',
          '告警已确认',
          snackPosition: SnackPosition.BOTTOM,
          backgroundColor: Colors.green,
          colorText: Colors.white,
        );
      }
    } catch (e) {
      Get.snackbar(
        '确认告警失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
      );
    }
  }
  
  // 查看告警详情
  void viewAlertDetail(int logId) {
    // 可以跳转到告警详情页面
    // Get.toNamed(Routes.alertDetail, arguments: logId);
    Get.snackbar(
      '查看告警详情',
      '告警ID: $logId',
      snackPosition: SnackPosition.BOTTOM,
    );
  }
  
  // 获取告警级别对应的颜色
  Color getAlertLevelColor(int? level) {
    String colorCode = _dataRepository.getAlertLevelColor(level);
    
    // 将十六进制颜色代码转换为Color对象
    return Color(int.parse(colorCode.substring(1, 7), radix: 16) + 0xFF000000);
  }
  
  // 获取告警状态对应的颜色
  Color getAlertStatusColor(int? status) {
    String colorCode = _dataRepository.getAlertStatusColor(status);
    
    // 将十六进制颜色代码转换为Color对象
    return Color(int.parse(colorCode.substring(1, 7), radix: 16) + 0xFF000000);
  }
  
  // 静默加载数据而不触发UI更新
  Future<void> silentRefreshData() async {
    debugPrint('开始静默刷新数据...');
    try {
      // 并行加载所有数据，使用缓存服务刷新数据
      await Future.wait([
        _productService.getHomeStatistics(forceRefresh: true).then((stats) {
          productCount.value = stats['productCount'] ?? 0;
          productsWithoutModelCount.value = stats['productsWithoutModelCount'] ?? 0;
        }).catchError((e) {
          debugPrint('静默加载产品统计错误: $e');
        }),
        
        _deviceService.getHomeStatistics(forceRefresh: true).then((stats) {
          deviceTotalCount.value = stats['totalCount'] ?? 0;
          deviceOnlineCount.value = stats['onlineCount'] ?? 0;
          deviceOfflineCount.value = stats['offlineCount'] ?? 0;
          deviceInactiveCount.value = stats['inactiveCount'] ?? 0;
          deviceDisabledCount.value = stats['disabledCount'] ?? 0;
        }).catchError((e) {
          debugPrint('静默加载设备统计错误: $e');
        }),
        
        _alertLogService.getHomeStatistics(forceRefresh: true).then((stats) {
          // 更新状态
          alertLogs.value = stats['logs'];
          alertLogsTotal.value = stats['total'];
          unconfirmedAlertCount.value = stats['unconfirmedCount'];
          alertGeneratedCount.value = stats['generatedCount'];
          alertRecoveredCount.value = stats['recoveredCount'];
          alertConfirmedCount.value = stats['confirmedCount'];
        }).catchError((e) {
          debugPrint('静默加载告警数据错误: $e');
        }),
      ]);
      
      debugPrint('静默刷新数据完成');
    } catch (e) {
      debugPrint('静默刷新数据错误: $e');
    }
  }
  
  // 加载所有统计数据
  Future<void> loadAllStatistics() async {
    debugPrint('开始加载所有统计数据...');
    try {
      // 根据当前状态设置loading标志
      if (!isRefreshing.value) {
        isLoading.value = true;
      }
      isLoadingAlerts.value = true;
      
      // 为每个异步操作创建一个Completer
      final productCompleter = Completer<void>();
      final deviceCompleter = Completer<void>();
      final alertCompleter = Completer<void>();
      
      // 并行执行所有统计数据加载，不使用延迟
      loadProductStatistics().then((_) {
        productCompleter.complete();
      }).catchError((e) {
        debugPrint('产品统计加载错误: $e');
        productCompleter.completeError(e);
      });
      
      loadDeviceStatistics().then((_) {
        deviceCompleter.complete();
      }).catchError((e) {
        debugPrint('设备统计加载错误: $e');
        deviceCompleter.completeError(e);
      });
      
      loadRecentAlertLogs().then((_) {
        debugPrint('告警日志加载完成');
        alertCompleter.complete();
      }).catchError((e) {
        debugPrint('告警日志加载出错: $e');
        alertCompleter.completeError(e);
      });
      
      // 等待所有操作完成
      await Future.wait([
        productCompleter.future.catchError((e) => debugPrint('产品统计等待错误: $e')),
        deviceCompleter.future.catchError((e) => debugPrint('设备统计等待错误: $e')),
        alertCompleter.future.catchError((e) => debugPrint('告警日志等待错误: $e')),
      ]);
      
    } catch (e) {
      Get.snackbar(
        '获取统计数据失败',
        e.toString(),
        snackPosition: SnackPosition.BOTTOM,
      );
    } finally {
      isLoading.value = false;
      isLoadingAlerts.value = false;
      isRefreshing.value = false;
    }
  }
  
  @override
  void onInit() {
    super.onInit();
    
    // 在onInit中初始化所有依赖
    try {
      debugPrint('HomeController初始化开始...');
      _userService = Get.find<UserService>();
      _authController = Get.find<AuthController>();
      _productService = Get.find<ProductService>();
      _deviceService = Get.find<DeviceService>();
      _alertLogService = Get.find<AlertLogService>();
      
      // 初始化DataRepository，用于获取颜色代码
      if (!Get.isRegistered<DataRepository>()) {
        debugPrint('DataRepository未注册，正在注册...');
        Get.put(DataRepository());
      }
      _dataRepository = Get.find<DataRepository>();
      
      // 先完成用户信息加载
      refreshUserInfo();
      
      // 减少延迟时间，确保在日志范围内执行
      Timer(const Duration(milliseconds: 100), () {
        debugPrint('执行loadAllStatistics...');
        loadAllStatistics();
      });
    } catch (e) {
      debugPrint('HomeController初始化失败: $e');
    }
  }
} 